<template>
  <div class="clock">
    <div>当&emsp;前&emsp;时间：{{ currentTime }}</div>
    <br>
    <div>网站停留时间：{{ duration }}秒</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount,onUnmounted } from 'vue';

// export default {
  // name: 'Clock',
  // setup() {
    const currentTime = ref('');

    function updateTime() {
      const now = new Date();
      currentTime.value = now.toLocaleTimeString();
    }

    let interval;

    onMounted(() => {
      updateTime();
      interval = setInterval(updateTime, 1000);
    });

    onBeforeUnmount(() => {
      clearInterval(interval);
    });

    // return {
    //   currentTime
    // };
//   }
// };
const duration = ref(0);

    let timerId;

    // 更新停留时间
    function updateDuration() {
      duration.value++;
    }

    // 在组件挂载后开始计时
    onMounted(() => {
      timerId = setInterval(updateDuration, 1000);
    });

    // 在组件卸载前清除计时器
    onUnmounted(() => {
      clearInterval(timerId);
    });

</script>

<style scoped>
.clock {
  color: rgb(0, 119, 255);
  /* font-size: 2em; */
  text-align: center;
  /* background-color: yellowgreen; */
  /* margin-top: 20px; */
  div{
    float: left;
    font-size: 13px;
    font-weight: 500;
  }
}
</style>